package com.jcxh.sg_exam.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jcxh.sg_exam.pojo.*;
import com.jcxh.sg_exam.pojo.dto.ShicaoDto;
import com.jcxh.sg_exam.pojo.vo.NewShicaoVo;
import com.jcxh.sg_exam.pojo.vo.ShicaoVo;
import com.jcxh.sg_exam.service.*;
import com.jcxh.sg_exam.utils.AdminThreadLocalUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author 鹏少
 * @Date 2025/1/14
 * @Date 9:46
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class ShicaoController {


    @Autowired
    private ShicaoService shicaoService;

    @Autowired
    private KaochangUserService kaochangUserService;

    @Autowired
    private KaochangService kaochangService;

    @Autowired
    private UserShicaoService userShicaoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private ParameterService parameterService;

    @Autowired
    private NewShicaoService newShicaoService;


    @ApiOperation("实操类别查询")
    @GetMapping("/getShicaoType")
    public Result getShicaoType() {
        try {
            List<Shicao> shicaoList = shicaoService.lambdaQuery().getBaseMapper().selectList(null);
            Set<String> collect = shicaoList.stream()
                    .map(Shicao::getType)
                    .collect(Collectors.toSet());
            return Result.success(collect);
        } catch (Exception e) {
            // 记录日志
            log.error("获取类别时发生异常", e);
            // 返回通用错误信息
            return Result.error("获取类别失败，请稍后再试。");
        }
    }


    @ApiOperation(value = "实操考题查询")
    @GetMapping("/getShicao")
    public Result getShicao(
            @ApiParam(value = "当前页码", required = true) @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @ApiParam(value = "每页大小(后端默认是10)", required = true) @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @ApiParam(value = "类别(默认查询全部)") String type,
            @ApiParam(value = "题目") String title) {

        IPage<Shicao> page = new Page<>(currentPage, pageSize);

        IPage<Shicao> shicaoPage = shicaoService.lambdaQuery()
                .eq(type != null, Shicao::getType, type)
                .like(title != null, Shicao::getTitle, title)
                .orderByAsc(Shicao::getId).page(page);
        return Result.success(shicaoPage);

    }

    @ApiOperation(value = "根据实操题id查询实操考题信息")
    @GetMapping("/selectShicao")
    public Result selectShicao(@ApiParam(value = "实操考题id", required = true) Integer id) {

        Shicao shicao = shicaoService.lambdaQuery().eq(Shicao::getId, id).one();

        return Result.success(shicao);

    }


    @ApiOperation(value = "实操考题修改按钮")
    @PutMapping("/updateShicao")
    public Result updateShicao(@Valid @RequestBody Shicao shicao, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            // 如果有验证错误，返回具体的错误信息
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//            String errorMessages = fieldErrors.stream()
//                    .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
//                    .collect(Collectors.joining(", "));
            String errorMessages = fieldErrors.stream()
                    .map(fieldError -> fieldError.getDefaultMessage())
                    .collect(Collectors.joining(", "));
            return Result.error("验证失败：" + errorMessages);
        }
        boolean flag = shicaoService.lambdaUpdate()
                .set(shicao.getTitle() != null, Shicao::getTitle, shicao.getTitle())
                .set(shicao.getType() != null, Shicao::getType, shicao.getType())
                .set(shicao.getAnswer() != null, Shicao::getAnswer, shicao.getAnswer())
                .eq(shicao.getId() != null, Shicao::getId, shicao.getId()).update();


        // 清空 Redis 中的 List
        redisTemplate.delete("shiCao");

        // 从数据库中获取数据并存入 Redis
        List<Shicao> shicaoList = shicaoService.lambdaQuery().list();
        redisTemplate.opsForList().rightPushAll("shiCao", shicaoList);
        if (flag) {
            return Result.success("修改成功");

        } else {
            return Result.error("修改失败");
        }

    }

    @ApiOperation(value = "实操考题删除按钮")
    @DeleteMapping("/deleteShicao")
    public Result deleteShicao(@ApiParam(value = "要删除实操题的id", required = true) @RequestParam(required = true) List<Integer> ids) {

        if (ids.size() == 0) {
            return Result.error("请勾选要删除的考题");
        }
        boolean removeByIds = shicaoService.removeByIds(ids);
        // 清空 Redis 中的 List
        redisTemplate.delete("shiCao");

        // 从数据库中获取数据并存入 Redis
        List<Shicao> shicaoList = shicaoService.lambdaQuery().list();
        // log.info("--------{}", shicaoList);
        redisTemplate.opsForList().rightPushAll("shiCao", shicaoList);
        if (removeByIds) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }

    }

    @ApiOperation(value = "新增实操考题按钮")
    @PostMapping("/addShicao")
    public Result addShicao(@ApiParam(value = "新增实操考题dto")
                            @Valid @RequestBody ShicaoDto shicaoDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            // 如果有验证错误，返回具体的错误信息
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//            String errorMessages = fieldErrors.stream()
//                    .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
//                    .collect(Collectors.joining(", "));
            String errorMessages = fieldErrors.stream()
                    .map(fieldError -> fieldError.getDefaultMessage())
                    .collect(Collectors.joining(", "));
            return Result.error("验证失败：" + errorMessages);
        }
        Shicao shicao = new Shicao();
        BeanUtils.copyProperties(shicaoDto, shicao);

        boolean save = shicaoService.save(shicao);

        // 清空 Redis 中的 List
        redisTemplate.delete("shiCao");

        // 从数据库中获取数据并存入 Redis
        List<Shicao> shicaoList = shicaoService.lambdaQuery().list();
        redisTemplate.opsForList().rightPushAll("shiCao", shicaoList);
        if (save) {
            return Result.success("添加实操考题成功");
        } else {
            return Result.error("添加实操考题失败");
        }

    }


    //旧版查看实操人员
    @GetMapping("/getShicaoInfo")
    public Result getShicaoInfo(@ApiParam(value = "当前页码", required = true) @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                @ApiParam(value = "每页大小(后端默认是10)", required = true) @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                @ApiParam(value = "姓名") String name,
                                @ApiParam(value = "工作单位") String workUnit,
                                @ApiParam(value = "身份证号") String idNumber) {

        IPage<ShicaoVo> kaochangUserList = kaochangUserService.getShicaoInfo(currentPage, pageSize, name, workUnit, idNumber);

        if (kaochangUserList.getRecords().isEmpty()) {
            return Result.error("暂无数据");
        }

        return Result.success(kaochangUserList);


    }

    //新版查看实操人员
    @GetMapping("/getNewShicaoInfo")
    public Result getNewShicaoInfo(@ApiParam(value = "当前页码", required = true) @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                   @ApiParam(value = "每页大小(后端默认是10)", required = true) @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                   @ApiParam(value = "姓名") String name,
                                   @ApiParam(value = "工作单位") String workUnit,
                                   @ApiParam(value = "身份证号") String idNumber,
                                   @ApiParam(value = "专项名称") String type) {

        IPage<NewShicaoVo> kaochangUserList = kaochangUserService.getNewShicaoInfo(currentPage, pageSize, name, workUnit, idNumber, type);

        if (kaochangUserList.getRecords().isEmpty()) {
            return Result.error("暂无数据");
        }

        return Result.success(kaochangUserList);


    }

    //新版查看检测专项 传递的参数为检测专项
    @GetMapping("/getItem")
    public Result getItem(String type) {
        if (StringUtils.isEmpty(type)) {
            return Result.error("参数不能为空!");
        }

        //根据检测专项名称查询出检测专项对应的id
        Category category = categoryService.lambdaQuery().eq(Category::getCategoryName, type).one();

        List<Item> itemList = itemService.lambdaQuery().eq(Item::getCategoryId, category.getCategoryId()).list();

        return Result.success(itemList);


    }

    //新版查看检测参数，根据检测项目
    @GetMapping("/getParameter")
    public Result getParameter(Integer itemId) {
        if (itemId == null) {
            return Result.error("参数不能为空!");
        }
        List<Parameter> parameterList = parameterService.lambdaQuery().eq(Parameter::getItemId, itemId).list();
        return Result.success(parameterList);

    }

    //新版设置分数
    @GetMapping("/setShicaoScore")
    @Transactional
    public Result setShicaoScore(@RequestParam("id") Integer kaochangId, Integer itemId, String score) {

        if (kaochangId == null || itemId == null || score == null) {
            return Result.error("参数不能为空!");
        }


        // 分数非空及范围校验
        if (score == null || score.trim().isEmpty()) {
            return Result.error("分数不能为空");
        }
        int scoreValue;
        try {
            scoreValue = Integer.parseInt(score);
        } catch (NumberFormatException e) {
            return Result.error("分数必须为数字");
        }
        if (scoreValue < 0 || scoreValue > 100) {
            return Result.error("分数不能小于0或者大于100");
        }

        // 查询 Item
        Item item = itemService.lambdaQuery().eq(Item::getItemId, itemId).one();
        if (item == null) {
            return Result.error("检测项目不存在");
        }

        // 查询 KaochangUser
        KaochangUser kaochangUser = kaochangUserService.lambdaQuery().eq(KaochangUser::getId, kaochangId).one();
        if (kaochangUser == null) {
            return Result.error("考生信息不存在");
        }

        // 查询 Category
        Category category = categoryService.lambdaQuery().eq(Category::getCategoryId, item.getCategoryId()).one();
        if (category == null) {
            return Result.error("分类信息不存在");
        }

        List<NewShicao> newShicaoList = newShicaoService.lambdaQuery()
                .eq(NewShicao::getName, kaochangUser.getName())
                .eq(NewShicao::getWorkUnit, kaochangUser.getWorkUnit())
                .eq(NewShicao::getIdNumber, kaochangUser.getIdNumber())
                .eq(NewShicao::getSubject, category.getCategoryName())
                .list();
        if (newShicaoList != null && !newShicaoList.isEmpty()) {
            long countC = newShicaoList.stream().filter(s -> "尚未通过检测项目".equals(s.getItem())).count();
            long countOther = newShicaoList.stream().filter(s -> item.getItemName().equals(s.getItem())).count();

            if (countC > 0) {
                return Result.error("操作失败,该人员已设置为C级!");
            }
            if (countOther > 0) {
                return Result.error("请勿重复设置分数！");
            }

        }


//        NewShicao selectNewShicao = newShicaoService.lambdaQuery().eq(NewShicao::getName, kaochangUser.getName())
//                .eq(NewShicao::getWorkUnit, kaochangUser.getWorkUnit())
//                .eq(NewShicao::getIdNumber, kaochangUser.getIdNumber())
//                .eq(NewShicao::getSubject, category.getCategoryName())
//                .eq(NewShicao::getItem, item.getItemName())
//                .one();
//        if (selectNewShicao != null) {
//
//            return Result.error("请勿重复设置分数！");
//        }


        // 构建 NewShicao 对象
        NewShicao newShicao = new NewShicao();
        newShicao.setKaochangUserId(kaochangUser.getId());
        newShicao.setName(kaochangUser.getName());
        newShicao.setWorkUnit(kaochangUser.getWorkUnit());
        newShicao.setIdNumber(kaochangUser.getIdNumber());
        newShicao.setSubject(category.getCategoryName());
        newShicao.setItem(item.getItemName());
        newShicao.setScore(score);
        newShicao.setCreateTime(LocalDateTime.now().toString());
        Admin admin = AdminThreadLocalUtil.getAdmin();
        newShicao.setPerson(admin != null ? admin.getUsername() : "未知管理员");
        newShicaoService.save(newShicao);

        return Result.success("分数设置成功");
    }


    //查看新版实操成绩
    @GetMapping("/getNewShicaoScore")
    public Result getNewShicaoScore(@ApiParam(value = "当前页码", required = true) @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                    @ApiParam(value = "每页大小(后端默认是10)", required = true) @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                    @ApiParam(value = "姓名") String name,
                                    @ApiParam(value = "工作单位") String workUnit,
                                    @ApiParam(value = "身份证号") String idNumber,
                                    @ApiParam(value = "检测专项") String subject
    ) {

        IPage<NewShicao> shicaoPage = new Page<>(currentPage, pageSize);

        shicaoPage = newShicaoService.lambdaQuery()
                .like(name != null, NewShicao::getName, name)
                .like(workUnit != null, NewShicao::getWorkUnit, workUnit)
                .like(idNumber != null, NewShicao::getIdNumber, idNumber)
                .eq(subject != null, NewShicao::getSubject, subject)
                .orderByDesc(NewShicao::getCreateTime)
                .page(shicaoPage);
        if (shicaoPage.getRecords().isEmpty()) {
            return Result.error("暂无数据");
        }

        return Result.success(shicaoPage);
    }

    //新版设置实操成绩为C级别
    @GetMapping("/setShicaoScoreC")
    public Result setShicaoScoreC(@RequestParam("id") Integer kaochangId, String type) {
        if (kaochangId == null || type == null) {
            return Result.error("参数不能为空!");
        }

        KaochangUser kaochangUser = kaochangUserService.lambdaQuery().eq(KaochangUser::getId, kaochangId).one();
        if (kaochangUser == null) {
            return Result.error("考生信息不存在");
        }

        List<NewShicao> newShicaoList = newShicaoService.lambdaQuery()
                .eq(NewShicao::getName, kaochangUser.getName())
                .eq(NewShicao::getWorkUnit, kaochangUser.getWorkUnit())
                .eq(NewShicao::getIdNumber, kaochangUser.getIdNumber())
                .eq(NewShicao::getSubject, type)
                .list();

        if (newShicaoList != null && !newShicaoList.isEmpty()) {
            long countC = newShicaoList.stream().filter(s -> "尚未通过检测项目".equals(s.getItem())).count();
            long countOther = newShicaoList.stream().filter(s -> !"尚未通过检测项目".equals(s.getItem())).count();

            if (countC > 0) {
                return Result.error("请勿重复设置分数！");
            }
            if (countOther > 0) {
                return Result.error("该人员已有检测项目成绩，不能设置为C级别");
            }
        }

        NewShicao newShicao = new NewShicao();
        newShicao.setKaochangUserId(kaochangUser.getId());
        newShicao.setName(kaochangUser.getName());
        newShicao.setWorkUnit(kaochangUser.getWorkUnit());
        newShicao.setIdNumber(kaochangUser.getIdNumber());
        newShicao.setSubject(type);
        newShicao.setItem("尚未通过检测项目");
        newShicao.setScore("0");
        newShicao.setCreateTime(LocalDateTime.now().toString());
        Admin admin = AdminThreadLocalUtil.getAdmin();
        newShicao.setPerson(admin != null ? admin.getUsername() : "未知管理员");

        newShicaoService.save(newShicao);
        return Result.success("分数设置成功");
    }


    //抽取实操考题
    @GetMapping("/getShicaoTitle")
    public Result getShicaoTitle(Integer id, String kaochangName) {

        UserShicao one = userShicaoService.lambdaQuery().eq(UserShicao::getKaochangUserId, id).one();
        if (one != null) {
            return Result.error("请勿重复抽取");
        }
        Kaochang kaochang = kaochangService.lambdaQuery().eq(Kaochang::getName, kaochangName).one();
        //获取考场类型
        String type = kaochang.getType();

        List<Shicao> shicaoList = redisTemplate.opsForList().range("shiCao", 0, -1);
        if (shicaoList == null || shicaoList.isEmpty()) {
            shicaoList = shicaoService.list();
        }

        List<Shicao> collect = shicaoList.stream().filter(s -> s.getType().equals(type)).collect(Collectors.toList());
        Collections.shuffle(collect);
        List<Shicao> list = collect.stream().limit(3).collect(Collectors.toList());
        //存入实操数据库
        UserShicao userShicao = new UserShicao();
        userShicao.setKaochangUserId(id);
        userShicao.setTitleOne(list.get(0).getId().toString());
        userShicao.setTitleTwo(list.get(1).getId().toString());
        userShicao.setTitleThree(list.get(2).getId().toString());
        userShicaoService.save(userShicao);

        return Result.success(list);


    }

    //查询实操考题
    @GetMapping("/selectShicaoTitle")
    public Result selectShicaoTitle(Integer id) {

        UserShicao userShicao = userShicaoService.lambdaQuery().eq(UserShicao::getKaochangUserId, id).one();
        if (userShicao == null) {
            return Result.error("请先抽取考题");
        }

        List<Integer> shicaoIds = Arrays.asList(
                Integer.parseInt(userShicao.getTitleOne()),
                Integer.parseInt(userShicao.getTitleTwo()),
                Integer.parseInt(userShicao.getTitleThree())
        );

        List<Shicao> shicaoList = shicaoService.listByIds(shicaoIds);

        return Result.success(shicaoList);


    }


    @Transactional
    @GetMapping("/setScore")
    public Result setScore(Integer id, String score) {

        Admin admin = AdminThreadLocalUtil.getAdmin();
        UserShicao userShicao = userShicaoService.lambdaQuery().eq(UserShicao::getKaochangUserId, id).one();
        if (userShicao == null) {
            return Result.error("请先抽取考题");
        }
        if (userShicao.getScore() != null) {
            return Result.error("该用户已有成绩");
        }
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        userShicaoService.lambdaUpdate()
                .set(UserShicao::getScore, score)
                .set(UserShicao::getPerson, admin.getUsername())
                .set(UserShicao::getCreateTime, formattedDateTime)
                .eq(UserShicao::getKaochangUserId, id).update();

        return Result.success("设置分数成功");
    }


}
